/**
 * 
 */
package com.playball.lottery.frm.yhzx;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.R;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.cache.MyPreference;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

//import com.playball.lottery.alipay.MobileSecurePayer;


/**
 * @author sunfanglei
 * @date 2014年2月27日
 */
public class LoginActivity extends BaseActivity {

	TextView tv_title;
	private TextView btn_title_left;
	private TextView btn_title_right;
	private TextView btn_bottom_left;
	private TextView btn_bottom_right;

	Button btn_login;
	AutoCompleteTextView et_userName;
	EditText et_userPassword;
	private SharedPreferences sp;
	private ShowTipDialog showdialog = new ShowTipDialog();
	private String loginName;
	private String loginPwd;
	private CheckBox cb_remember_password;

	Button tv_register_now;
	Button tv_aplipay_login;
	static String TAG = "Alipay login";
	private ProgressDialog mProgress = null;
	private TextView forgetPass;
	static private String mUserIdText;
	private TextView mToken;
	private String mTokenText;
	private int mSelectType = 0;
	public static final int FASTLOGON = 0;
	public static final int DATAAUTH = 1;
	public static final String PREFS_NAME = "perfAccount";

	public static int alipayLoginTimes = -1;

	/** 判断是否从推送通知过来 */
	private Boolean ifPush;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_new_login_layout);

		tv_title = (TextView) findViewById(R.id.top_title_info);
		btn_title_left = (TextView) findViewById(R.id.top_title_back);
		btn_title_right = (TextView) findViewById(R.id.top_title_right_btn);
		// btn_bottom_left = (TextView) findViewById(R.id.bottom_left_btn);
		// btn_bottom_right = (TextView) findViewById(R.id.bottom_right_btn);
		btn_login = (Button) findViewById(R.id.btn_login);
		et_userName = (AutoCompleteTextView) findViewById(R.id.et_user_name);
		et_userPassword = (EditText) findViewById(R.id.et_user_password);
		cb_remember_password = (CheckBox) findViewById(R.id.cb_remember_password);
		tv_register_now = (Button) findViewById(R.id.btn_regester_now);
		tv_aplipay_login = (Button) findViewById(R.id.btn_aplipay_login);
		forgetPass = (TextView) findViewById(R.id.tv_forget_pass);
		forgetPass.setText(Html.fromHtml("<u>找回密码</u>"));
		tv_title.setText("欢迎登录");
		// btn_title_left.setVisibility(View.INVISIBLE);
		btn_title_right.setVisibility(View.INVISIBLE);
		// btn_bottom_left.setVisibility(View.INVISIBLE);
		// btn_bottom_left.setText("<<<<<<<<");
		ifPush = getIntent().getBooleanExtra("ifPush", false);
		IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
		filter.addDataScheme("package");
//		registerReceiver(mPackageInstallationListener, filter);

		// 返回
		btn_title_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LoginActivity.this.finish();
			}
		});

//		tv_aplipay_login.setOnClickListener(new View.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				performPay(FASTLOGON);
//			}
//		});

		// 注册按钮
		tv_register_now.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, JddRegisterActivity.class);
				intent.putExtra("LoginFragment", 0);
				//startActivity(intent);
				//传值至注册页面
				startActivityForResult(intent, DefConstants.REQ_CODE_BUY_REGISTER);
				//finish();
			}
		});

		// 忘记密码
		forgetPass.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, JddFindPassActivity.class);
				intent.putExtra("user_name", et_userName.getText().toString());
				startActivityForResult(intent, DefConstants.REQ_CODE_FIND_PASSWORD);
			}
		});
		sp = this.getSharedPreferences("userNamesFile", MODE_PRIVATE);

		et_userName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				String[] allUserName = new String[sp.getAll().size()];// sp.getAll().size()返回的是有多少个键值对
				allUserName = sp.getAll().keySet().toArray(new String[0]);

				List<String> listUser = new ArrayList<String>();
				for (int i = 0; i < allUserName.length; i++) {
					// System.out.println("key:" + allUserName[i]);
					if ("".equals(allUserName[i]) || "last-user".equals(allUserName[i])) {
						// 排除最后登录用户名和用户名为空的项
					} else {
						listUser.add(allUserName[i]);
					}
				}

				ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this,
						android.R.layout.simple_dropdown_item_1line, listUser);
				et_userName.setAdapter(adapter);// 设置数据适配器
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String pwdString = sp.getString(et_userName.getText().toString(), "");
				et_userPassword.setText(pwdString);
			}
		});

		btn_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					if (et_userName.getText().toString().equals("")) {
						Toast.makeText(LoginActivity.this, R.string.user_name_cannot_be_empty, Toast.LENGTH_LONG)
								.show();
					} else if (et_userPassword.getText().toString().equals("")) {
						Toast.makeText(LoginActivity.this, R.string.password_cannot_be_empty, Toast.LENGTH_LONG).show();
					} else if (et_userName.getText().toString().getBytes("gbk").length < 4
							| et_userName.getText().toString().getBytes("gbk").length > 16) {
						Toast.makeText(LoginActivity.this, R.string.chinese_characters_numbers_and_letters,
								Toast.LENGTH_LONG).show();
					} else {
						AsyncLoader task = new AsyncLoader();
						task.execute("101");
					}
				} catch (Exception e) {
					// e.printStackTrace();
				}
			}
		});

		// btn_bottom_left.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// setResult(RESULT_OK);
		// finish();
		// }
		// });
	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_CANCELED);
			if(ifPush){
				Intent intent = new Intent(this, JddMainActivity.class);
				startActivity(intent);
			}
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	};

	public class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(LoginActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				loginName = et_userName.getText().toString();
				loginPwd = et_userPassword.getText().toString();
				// 设置请求所需参数
				JSONObject param = new JSONObject();
				param.put("Name", loginName);
				param.put("Pw", loginPwd);// Password
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						// 保存密码
						if (cb_remember_password.isChecked()) {
							Editor edit = sp.edit();
							edit.putString(loginName, loginPwd);
							edit.putString("last-user", loginName);
							edit.commit();
						} else {
							sp.edit().remove(loginName).commit();
						}

						// 保存用户名，密码,方便后边调用
						ApplicationData.getInstance().setUserName(loginName);
						ApplicationData.getInstance().setUserPassword(loginPwd);
						ApplicationData.getInstance().setUserID(js.getString("Data"));
						MyPreference.getInstance(LoginActivity.this).setUserId(
								ApplicationData.getInstance().getUserID());

//						et_userName.setText("");
						et_userPassword.setText("");

						String recharge = getIntent().getStringExtra("recharge");
						String showBalance = getIntent().getStringExtra("showBalance");
						if (recharge == null || "".equals(recharge)) {
						} else {
							Intent intent = new Intent(LoginActivity.this, JddRechargeListActivity.class);
							intent.putExtra("recharge", recharge);
							intent.putExtra("showBalance", showBalance);
							startActivity(intent);
						}
						
						EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);
						
						setResult(RESULT_OK);
						finish();
					} else {
						Toast.makeText(LoginActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(LoginActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}
	}


	//
	// close the progress bar
	// 关闭进度框
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}


	public class AsyncLoaderAlipayLogin extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(LoginActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				// 设置请求所需参数
				JSONObject param = new JSONObject();
				param.put("AlipayID", params[0].replace("\"", ""));
				String action = "116";
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						alipayLoginTimes = -1;
						jsonParser = new JSONTokener(js.getString("Data"));
						js = (JSONObject) jsonParser.nextValue();
						loginName = js.getString("Name");
						String id = js.getString("ID");
						loginPwd = "";
						ApplicationData.getInstance().setUserName(loginName);
						ApplicationData.getInstance().setUserID(id);
						ApplicationData.getInstance().setUserPassword(loginPwd);
						MyPreference.getInstance(LoginActivity.this).setUserId(id);
						// 跳转
						setResult(RESULT_OK);
						// 销毁本页面
						LoginActivity.this.finish();
					} else {
						if (alipayLoginTimes > 0) {
							alipayLoginTimes = alipayLoginTimes - 1;
							showdialog.closeDialog();
							Thread.sleep(2000);
							AsyncLoaderAlipayLogin task = new AsyncLoaderAlipayLogin();
							task.execute(mUserIdText.toString());
						} else {
							Toast.makeText(LoginActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
							showdialog.closeDialog();
						}
					}
				} catch (Exception ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(LoginActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
//		try {
//			unregisterReceiver(mPackageInstallationListener);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			// e.printStackTrace();
//		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == DefConstants.REQ_CODE_FIND_PASSWORD && resultCode == RESULT_OK) {
			finish();
		}
		//注册成功返回至彩种投注列表页面
		if(requestCode==DefConstants.REQ_CODE_BUY_REGISTER && resultCode==RESULT_OK)
		{
			setResult(RESULT_OK);
			finish();
		}
	}
	
}
